package com.cn.service.imppl;

import com.alibaba.fastjson.JSON;
import com.cn.pojo.PageResult;
import com.cn.pojo.RequestParams;
import com.cn.pojo.TbHotel;
import com.cn.service.IHotelService;
import org.apache.lucene.index.Term;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IHotelServiceImpl implements IHotelService {

    @Autowired
    private RestHighLevelClient client;


    /**
     * 分页查询方式
     * @param params
     * @return
     * @throws IOException
     */
    @Override
    public PageResult search(RequestParams params) throws IOException {
        //1.准备发送
        SearchRequest request = new SearchRequest("hotel");
        //2.准备布尔条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //3.判断是否存在
        String key = params.getKey();
        if (key==null || "".equals(key)){
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else {
            boolQuery.must(QueryBuilders.matchQuery("name",key));
        }
        Integer size = params.getSize();
        Integer page = params.getPage();
        request.source().from((page - 1) * size).size(size);
        request.source().query(boolQuery);

        String location = params.getLocation();

        //得出具体路径
        if (location!=null && !location.equals("")){
            request.source().sort(SortBuilders
                    .geoDistanceSort("lonAndLat",new GeoPoint(location))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS));
        }

        //相关性算法
        FunctionScoreQueryBuilder scoreQuery = QueryBuilders.functionScoreQuery(
                boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                }
        );
        request.source().query(scoreQuery);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        return  handleResponse(response);
    }

    /**
     * 添加聚合桶
     * @param params
     * @return
     * @throws IOException
     */
    @Override
    public Map<String, List<String>> getFilter(RequestParams params) throws IOException {
        //1.准备request
        SearchRequest request = new SearchRequest("hotel");
        //2.准备DSL
        //3.quert
        //4.设置size
        request.source().size(0);
        //5.聚合
        buildAggregation(request);
        //6.发出请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //7.解析结果
        Map<String,List<String>> result = new HashMap<>();
        Aggregations aggregations = response.getAggregations();
        //8.根据品牌名称,获取结果
        List<String> brandList = getAggByName(aggregations,"brandAgg");
        result.put("品牌",brandList);
        //9.根据品牌名称,获取品牌结果
        List<String> cityList = getAggByName(aggregations,"cityAgg");
        result.put("城市",cityList);
        List<String> starList = getAggByName(aggregations,"starAgg");
        result.put("星级",starList);
        return result;
    }

    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        Terms brandTerms = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            brandList.add(keyAsString);
        }
        return brandList;
    }

    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand.keyword")
                .size(100));
        request.source().aggregation(AggregationBuilders
                .terms("cityAgg")
                .field("city.keyword")
                .size(100));
        request.source().aggregation(AggregationBuilders
                .terms("starAgg")
                .field("starName.keyword")
                .size(100));
    }


    private PageResult handleResponse(SearchResponse response) {
        List<TbHotel> tbHotels = new ArrayList<>();
        long value = response.getHits().getTotalHits().value;
        SearchHits hits = response.getHits();
        SearchHit[] hits1 = hits.getHits();
        for (SearchHit hit : hits1) {
            TbHotel tbHotel = JSON.parseObject(hit.getSourceAsString(), TbHotel.class);
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length>0){
                Object sortValue = sortValues[0];
                tbHotel.setDistance(sortValue);
            }
            tbHotels.add(tbHotel);
        }
        PageResult pageResult = new PageResult();
        pageResult.setHotels(tbHotels);
        pageResult.setTotal(value);
        return pageResult;
    }

}
